CKEDITOR.plugins.add('variables', {
	requires : ['richcombo'], // , 'styles' ],
	init : function(editor) {
		var config = editor.config, lang = editor.lang.format;

		var URL = $(editor.element.$).attr("data-URL");
		$.ajax({
			"dataType" : 'json',
			"type" : "POST",
			"url" : URL,
			"async" : false,
			"success" : function(data) {
				for(var i = 0; i < data.length; i++) {
					var obj = data[i];
					var variables = [];

					for(var j = 0; j < obj.variables.length; j++) {
						variables.push(obj.variables[j]);
					}

					editor.ui.addRichCombo(obj.name, {
						label : obj.name,
						title : obj.name,
						voiceLabel : obj.name,
						className : 'cke_format',
						multiSelect : false,
						variables : variables,
						modes : {
							wysiwyg : 1,
							source : 1
						},

						panel : {
							css : [config.contentsCss, CKEDITOR.getUrl(editor.skinPath + 'editor.css')],
							voiceLabel : lang.panelVoiceLabel
						},

						init : function() {
							this.startGroup(this.label);
							for(var j = 0; j < this.variables.length; j++) {
								this.add("${" + this.variables[j].variableName + "}", this.variables[j].variableName, this.variables[j].variableName);
							}
						},
						onClick : function(value) {
							editor.focus();
							editor.fire('saveSnapshot');
							if(editor.mode == 'source') {
								var input = $(editor.element.$).next().find('.cke_contents .cke_enable_context_menu')[0];
								input.focus();

								if(document.selection) {
									//For browsers like Internet Explorer
									var sel = document.selection.createRange();
									sel.text = value;
									input.focus();
								} else {
									if( typeof input.selectionStart == 'undefined') {
										input.selectionStart = 0;
										input.selectionEnd = 0;
										input.value = "";
									}

									var start = input.selectionStart;
									var end = input.selectionEnd;
									input.value = input.value.substr(0, start) + value + input.value.substr(end);
									var pos;
									pos = start + value.length;

									input.selectionStart = pos;
									input.selectionEnd = pos;
								}
							} else {
								editor.insertText(value);
							}

							editor.fire('saveSnapshot');
						}
					});
				}
			}
		});
	}
});
